import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/11/4 21:02
 */


class MyThreadPool{
    //1.描述任务，直接用 Runnable 就不需要创建类了
    //2.使用一个数据结构去组织若干个任务
    private BlockingDeque<Runnable> queue = new LinkedBlockingDeque<>();
    //3.描述一个线程,工作线程任务就是从任务队列中取任务并执行
    static class Worker extends Thread{
        //此时若干个线程都持有上面的任务队列了
        private BlockingDeque<Runnable> queue = null;

        public Worker(BlockingDeque<Runnable> queue) {
            this.queue = queue;
        }

        @Override
        public void run() {
           //需要拿到上面队列
            while (true){
                try {
                    //循环获取任务队列中的任务
                   Runnable runnable = queue.take();
                   //获取到以后，就执行任务
                   runnable.run();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    //4.创建一个数据结构去组织若干个线程
    private List<Thread> workers = new ArrayList<>();

    public MyThreadPool(int n){
        //在构造方法中创造出多个线程，放到上述数组中
        for (int i = 0; i < n; i++) {
            Worker worker = new Worker(queue);
            worker.start();
            workers.add(worker);
        }
    }
    //5.创建一个方法，能够往里面加任务
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}



public class Test {
    public static void main(String[] args) {
        MyThreadPool pool = new MyThreadPool(10);
        for (int i = 0; i < 100; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello threadpool!");
                }
            });
        }
    }



    public static void main1(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(10);
        while (true){
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello threadpool!");
                }
            });
        }
    }
}
